﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using reminder_csh.Entities;
using reminder_csh.IManager;

namespace reminder_csh {
    class TaskManagerImpl : ITaskManager, IDisposable {
        private MyDbContext db=new MyDbContext();
        public void Dispose() {
            db.Dispose();
        }

        public void CreateTask(Task task) {
            if (task==null)
                throw new NullReferenceException("task is null");
            db.TaskDbSet.Add(task);
            db.SaveChanges();
        }

        public void UdateTask(Task task) {
            if (task==null)
                throw new NullReferenceException("task is null");
            db.Entry(task).State=EntityState.Modified;
            db.SaveChanges();

        }

        public void DeleteTask(Task task) {
            if (task==null)
                throw new NullReferenceException("task is null");
            var id=task.Id;
            var t=db.TaskDbSet.Find(id);
            if (t==null)
                throw new NullReferenceException("task not in db");
            db.TaskDbSet.Remove(t);
            db.SaveChanges();
        }

        public List<Task> FindAllTasks() {
            return db.TaskDbSet.ToList();
           
        }

        public Task FindTaskById(int id) {
            var t=db.TaskDbSet.Find(id);
            return t;
        }

        public List<Task> FindAllDoneTasks() {
            var list=FindAllTasks();
            return list.Select(x => x).Where(x => x.Done).ToList();
        }

        public List<Task> FindAllTasksOverDeadline() {
            var list=FindAllTasks();
            return list.Select(x => x).Where(x => x.Deadline<DateTime.Now&&x.Done==false).ToList();

        }
    }
}
